package com.t2two.example.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * websocket的处理类。 作用相当于HTTP请求中的controller
 */
@Component
@Slf4j
@ServerEndpoint(value = "/newWebsocket/{userId}", encoders = {UserInfoWebServerEncoder.class})
public class NewWebSocketServer {

    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
//    private static int onlineCount = 0;
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    /**concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。*/
    private static ConcurrentHashMap<Integer, NewWebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private Integer userId;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") Integer userId) {
        this.session = session;
        this.userId=userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //加入set中
            webSocketMap.put(userId,this);
        }else{
            //加入set中
            webSocketMap.put(userId,this);
            //在线数加1
            addOnlineCount();
        }
    }

    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 服务端接收客户端消息的方法
     * @param message
     */
    @OnMessage
    public void onMessage(String message){
        log.info("NewWebSocketServer_onMessage_info_message {}",message);
        // 处理需要通过消息来审批、操作的内容

    }

    /**
     * 获得此时的在线人数
     * @return
     */
    public static int getOnlineCount() {
        return onlineCount.get();
    }

    /**
     * 在线人数加1
     */
    public static void addOnlineCount() {
        onlineCount.incrementAndGet();
    }

    /**
     * 在线人数减1
     */
    public static void subOnlineCount() {
        onlineCount.decrementAndGet();
    }

    public static void sendRemindMessage(String msg,Integer userId){
        if(webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendRemindMessage(msg);
        }
    }
    public void sendRemindMessage(String msg){
        try {
            this.session.getBasicRemote().sendObject(msg);
        }catch (Exception e){

        }
    }

}
